"""
⚠️ 已废弃的API类

此类已被废弃，请使用新的API结构：
- 文件位置: api/id_photo_service.py
- 类名: IDPhotoService
- 使用方法: from api.id_photo_service import IDPhotoService

新的API提供了：
1. 更好的文件管理（存储到openid目录）
2. 自动清理功能（7天后自动删除）
3. 更完善的错误处理
4. RESTful API接口
5. 详细的日志记录

示例：
    from api.id_photo_service import IDPhotoService
    service = IDPhotoService()
    result = service.process_photo("image.jpg", "一寸", "蓝色")
"""

import warnings
from gradio_client import Client, handle_file
from typing import Literal, Optional, Union, List, Dict, Tuple
import os

warnings.warn(
    "IDPhotoAPI类已废弃，请使用api.id_photo_service.IDPhotoService",
    DeprecationWarning,
    stacklevel=2
)


class IDPhotoAPI:
    def __init__(self):
        """初始化API客户端"""
        self.client = Client("https://swanlab-hivisionidphotos.ms.show/")
        self.available_sizes = [
            "一寸\t\t(413, 295)", "二寸\t\t(626, 413)",
            "小一寸\t\t(378, 260)", "小二寸\t\t(531, 413)",
            "大一寸\t\t(567, 390)", "大二寸\t\t(626, 413)",
            "五寸\t\t(1499, 1050)", "教师资格证\t\t(413, 295)",
            "国家公务员考试\t\t(413, 295)", "初级会计考试\t\t(413, 295)",
            "英语四六级考试\t\t(192, 144)", "计算机等级考试\t\t(567, 390)",
            "研究生考试\t\t(709, 531)", "社保卡\t\t(441, 358)",
            "电子驾驶证\t\t(378, 260)", "美国签证\t\t(600, 600)",
            "日本签证\t\t(413, 295)", "韩国签证\t\t(531, 413)"
        ]

    def get_available_sizes(self) -> List[str]:
        """获取可用的证件照尺寸选项"""
        return self.available_sizes

    def update_watermark_text_visibility(
            self,
            choice: Literal['不添加', '添加'] = "不添加",
            language: Literal['zh', 'en', 'ko', 'ja'] = "zh"
    ) -> Dict[str, Union[str, float]]:
        """
        更新水印文本可见性

        参数:
            choice: 水印选项，'不添加'或'添加'
            language: 语言选择，'zh', 'en', 'ko'或'ja'

        返回:
            包含水印设置的字典
        """
        result = self.client.predict(
            choice=choice,
            language=language,
            api_name="/update_watermark_text_visibility"
        )

        # 处理返回的update对象
        if isinstance(result[0], dict) and result[0].get('__type__') == 'update':
            return {
                'text': "",
                'color': "#FFFFFF",
                'size': 20.0,
                'opacity': 0.15,
                'angle': 30.0,
                'space': 25.0
            }

        return {
            'text': result[0],
            'color': result[1],
            'size': result[2],
            'opacity': result[3],
            'angle': result[4],
            'space': result[5]
        }

    def process_photo(
            self,
            input_image: str,
            size_list_option: str = "一寸\t\t(413, 295)",
            color_option: Literal[
                '蓝色', '白色', '红色', '黑色', '深蓝色', '浅灰色', '美式证件照', '自定义(RGB)', '自定义(HEX)'] = "蓝色",
            watermark_option: Literal['不添加', '添加'] = "不添加",
            watermark_text: str = "",
            language: Literal['zh', 'en', 'ko', 'ja'] = "zh",
    ) -> Dict[str, Union[str, List[Dict[str, str]]]]:
        """
        处理图像生成证件照

        参数:
            input_image: 输入图像路径
            size_list_option: 尺寸选项
            color_option: 背景颜色
            watermark_option: 是否添加水印
            watermark_text: 水印文字
            language: 语言选择

        返回:
            包含处理结果的字典:
            {
                'standard': 标准照路径,
                'hd': 高清照路径,
                'transparent_standard': 透明标准照路径,
                'transparent_hd': 透明高清照路径,
                'layout': 排版照路径,
                'social_media': [{'image': 图片路径, 'caption': 说明}, ...],
                'message': 通知消息
            }
        """
        # 验证尺寸选项是否有效
        if size_list_option not in self.available_sizes:
            raise ValueError(f"无效的尺寸选项，请使用get_available_sizes()获取有效选项")

        # 检查输入文件是否存在
        if not os.path.exists(input_image):
            raise FileNotFoundError(f"输入图片不存在: {input_image}")

        # 调用API处理图片
        result = self.client.predict(
            input_image=handle_file(input_image),
            mode_option="尺寸列表",
            size_list_option=size_list_option,
            color_option=color_option,
            render_option="纯色",
            image_kb_options="不设置",
            custom_color_R=0,
            custom_color_G=0,
            custom_color_B=0,
            custom_color_hex_value="000000",
            custom_size_height=413,
            custom_size_width=295,
            custom_size_height_mm=35,
            custom_size_width_mm=25,
            custom_image_kb=50,
            language=language,
            matting_model_option="modnet_photographic_portrait_matting",
            watermark_option=watermark_option,
            watermark_text=watermark_text,
            watermark_text_color="#FFFFFF",
            watermark_text_size=20,
            watermark_text_opacity=0.15,
            watermark_text_angle=30,
            watermark_text_space=25,
            face_detect_option="retinaface-resnet50",
            head_measure_ratio=0.2,
            top_distance_max=0.12,
            whitening_strength=2,
            image_dpi_option="不设置",
            custom_image_dpi=300,
            brightness_strength=0,
            contrast_strength=0,
            sharpen_strength=0,
            saturation_strength=0,
            plugin_option=["排版照裁剪线"],
            print_switch="六寸",
            api_name="/process"
        )

        # 解析返回结果
        def extract_path(item):
            """从不同类型的返回项中提取路径"""
            if isinstance(item, str):
                return item
            elif isinstance(item, dict):
                if item.get('__type__') == 'update':
                    return item.get('value')
                elif 'image' in item:
                    return item['image']
                elif 'path' in item:
                    return item['path']
            return None

        standard = extract_path(result[0]) if len(result) > 0 else None
        hd = extract_path(result[1]) if len(result) > 1 else None
        transparent_standard = extract_path(result[2]) if len(result) > 2 else None
        transparent_hd = extract_path(result[3]) if len(result) > 3 else None

        # 处理排版照
        layout = None
        if len(result) > 4:
            layout_item = result[4]
            if isinstance(layout_item, dict) and layout_item.get('__type__') == 'update':
                layout = layout_item.get('value')
            elif isinstance(layout_item, str):
                layout = layout_item

        # 处理社交媒体模板照
        social_media = []
        if len(result) > 5:
            social_item = result[5]
            if isinstance(social_item, dict) and social_item.get('__type__') == 'update':
                social_list = social_item.get('value', [])
                if isinstance(social_list, list):
                    for item in social_list:
                        if isinstance(item, dict):
                            social_media.append({
                                'image': item.get('image'),
                                'caption': item.get('caption')
                            })

        # 处理消息
        message = ""
        if len(result) > 6:
            message_item = result[6]
            if isinstance(message_item, dict) and message_item.get('__type__') == 'update':
                message = str(message_item.get('value', ''))
            else:
                message = str(message_item)

        return {
            'standard': standard,
            'hd': hd,
            'transparent_standard': transparent_standard,
            'transparent_hd': transparent_hd,
            'layout': layout,
            'social_media': social_media,
            'message': message
        }